package com.team.cloudsharing.dao.feedback;

import java.io.Serializable;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.team.cloudsharing.ultis.CastArrayList;

@Repository
public class FeedbackDAOImpl implements FeedbackDAO{
	
	final static Logger logger = Logger.getLogger(FeedbackDAOImpl.class);
	
	@Autowired
	SessionFactory sessionFactory;
	
	@Override
	@Transactional
	public long insertFeedback(FeedbackDO feedbackDO) {
		long feedbackId = -1;
		Session session = null;
		if (feedbackDO != null) {
			try {
				session = sessionFactory.openSession();
				Transaction tx = session.beginTransaction();
				session.saveOrUpdate(feedbackDO);
				tx.commit();
				Serializable id = session.getIdentifier(feedbackDO);
				feedbackId = (Long) id;
			} catch (Exception e) {
				logger.error(e.getMessage());
			} finally {
				try {
					session.close();
				} catch (Exception e2) {
					logger.error(e2.getMessage());
				}
			}
		}
		return feedbackId;
	}

	@Override
	public List<FeedbackDO> findAllFeedback() {
		List<FeedbackDO> listFeedbackDOs = null;
		Session session = null;
		try {
			session = sessionFactory.openSession();
			session.beginTransaction();
			Criteria criteria = session.createCriteria(FeedbackDO.class);
			listFeedbackDOs = CastArrayList.castCollection(criteria.list(), FeedbackDO.class);
		} catch (Exception e) {
			logger.error(e.getMessage());
		} finally {
			try {
				session.close();
			} catch (Exception e2) {
				logger.error(e2.getMessage());
			}
		}
		return listFeedbackDOs;
	}

	@Override
	public boolean deleteFeedback(long feedbackId) {
		boolean statusDelete = false;
		Session session = null;
		try {
			session = sessionFactory.openSession();
			FeedbackDO feedbackDO = (FeedbackDO) session.load(FeedbackDO.class, feedbackId);
			Transaction tx = session.getTransaction();
			session.getTransaction().begin();
			session.delete(feedbackDO);
			tx.commit();
			statusDelete = true;
		} catch (Exception e) {
			statusDelete = false;
			logger.error(e.getMessage());
		} finally {
			try {
				session.close();
			} catch (Exception e2) {
				logger.error(e2.getMessage());
			}
		}
		return statusDelete;
	}

}
